<?php

class Core_Backend_Component_Article_Controller_Content extends Dcmp_Component_Controller {
	
    public function indexAction($pageindex = 1, $pagesize = 20, $sort = 'modifiedtime', $dir = 'desc', $areaid = 0) {
        $this->getHistory()->record();
        $validator = $this->getRequest()->getValidator('filter');
        $collection = App::getModel('article/collection_content')
                        ->joinAccount()
                        ->joinCategory()
                        ->pagination($pageindex, $pagesize)
                        ->sortBy($sort, $dir);
        if (!$this->getIdentity()->isInRole('article_manager')) {
        	$collection->filterByOwnerId($this->getIdentity()->getId());
        }
        if ($validator->isNotEmpty('title')) {
            $collection->filterByTitle($validator->getValue('title'));
        }
        if ($validator->isNotEmpty('status')) {
            $collection->filterByStatus($validator->getValue('status'));
        }
        if ($validator->isNotEmpty('top')) {
            $collection->filterByTop($validator->getValue('top'));
        }
        if ($validator->isNotEmpty('new')) {
            $collection->filterByNew($validator->getValue('new'));
        }
        if ($validator->isNotEmpty('hot')) {
            $collection->filterByHot($validator->getValue('hot'));
        }
        if ($validator->isNotEmpty('categoryname')) {
            $collection->filterByCategoryName($validator->getValue('categoryname'));
        }
        $collection->load();
        $records = $collection->loadCount();
        return $this->viewResult(array('list' => $collection, 'records' => $records));
    }

    public function createAction() {
        $categories = App::getModel('article/collection_category')->load();
        return $this->viewResult(array('categories' => $categories));
    }

    public function editAction($id) {
        $model = App::getModel('article/content')->load($id);
        $this->getPage()->getNavigation()->addLabel($model->getTitle());
        return $this->createAction($model->getAreaId())->setModel($model);
    }

    public function deleteAction($ids){
        App::getModel('article/content')->deleteBatch($ids);
        return $this->redirectResult($this->getHistoryUrl('article/content/index'));
    }

    public function generateTagAction() {
        $articles = App::getModel('article/collection_content')->load();
        $tagModel = App::getModel('tag/keyword');
        $transaction = Kd_Db_Factory::getTransaction();
        try {
            $transaction->begin();
            foreach ($articles as $article) {
                $tags = explode(' ', $article->getTag());
                $tagModel->removeTagRecord($article->getId(), 'article', $transaction)
                         ->addTagRecord($tags, $article->getId(), 'article', $transaction);
            }
            $transaction->commit();
        } catch (Exception $ex) {
            $transaction->rollback();
            throw $ex;
        }
        $this->getMessager()->addInform($this->__f('share.message.success'));
        return $this->redirectResult($this->getHistoryUrl('article/content/index'));
    }

    public function previewAction($id) {
        $this->getSession()->set('article_preview', TRUE);
//        $frontendPath = '';
//        $model = App::getModel('article/content')->load($id);
//        $template = new Core_Template();
//        $template->assign('content', $model);
//        $content = $template->render(BP.'pri'.DS.'template'.DS.'stable'.DS.'frontend'.DS.'default'.DS.'component'.DS.'article'.DS.'content'.DS.'content.phtml');
        return $this->viewResult(array('url' => '/article/content/preview/id/' . $id));
    }

    //only for .net
//    public function sendAction($id){
//        $model = App::getModel('article/content')->load($id);
//        $result = $this->previewAction($id);
//        file_put_contents('e:/webroot/csddt/Pub/static/'.$model->getId().'.html', $result->getContent());
//        if ($handle = opendir(DP_PUB.'media'.DS.'editor'.DS.'images')) {
//            while (false !== ($file = readdir($handle))) {
//                if ($file != "." && $file != "..") {
//                    if(!file_exists('e:/webroot/csddt/Pub/media/editor/images'.DS.$file)){
//                        copy(DP_PUB.'media'.DS.'editor'.DS.'images'.DS.$file, 'e:/webroot/csddt/Pub/media/editor/images'.DS.$file);
//                    }
//                }
//            }
//        }
//        $this->getMessager()->addInform('send success!!');
//        return $this->redirectResult($this->getHistoryUrl('article/content/index'));
//    }

//    public function applyPostAction() {
//        if ($this->saveModel('draft', $model)) {
//            return $this->redirectResult($this->getUrl(array('id' => $model->getIdValue()), 'edit'));
//        }
//        return $this->createAction()->setModel($model);
//    }

    public function savePostAction($status = 'draft') {
        $data = $this->getRequest()->getForm('content');
        $model = App::getModel('article/content');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }
        $model->addData($data)->setStatus($status);
        $savedModel = $model;
        if (($errors = $model->validate() === TRUE)) {
            $model->save();
            $this->getMessager()->addInform($this->__('share.message.success'));
            return $this->redirectResult($this->getHistoryUrl('article/content/index'));
        } else {
            $this->getMessager()->addError($this->__('share.message.fail'))
                    ->addError($errors);
			return $this->createAction()->setModel($model);                    
        }
    }

    public function reviewAction($ids, $status, $statusmessage = ''){
        if($status == 'published'){
            App::getModel('article/content')->publish($ids);
        }elseif($status == 'forbidden'){
            App::getModel('article/content')->forbid($ids, $statusmessage);
        }
        return $this->redirectResult($this->getHistoryUrl('article/content/index'));
    }
}